<template>
  <div class="edit">
    <a-modal v-model:visible="visible" title="编辑策略" @ok="onOk" :destroyOnClose="true">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="策略内容" v-bind="validateInfos.content">
          <a-textarea v-model:value="form.state.content" placeholder="请输入" :auto-size="{ minRows: 8, maxRows: 20 }" :maxlength="1000" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, ref, watch } from 'vue'

  import { requestEditStrategy } from '/@/api/business/space'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const props = defineProps({
    visible: { type: Boolean, default: false },
    data: { type: Object, default: () => {} },
  })

  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) {
        initData()
        form.state.content = JSON.stringify(props.data, null, 4)
      }
    },
  )
  const initData = () => {
    resetFields()
  }
  /** 表单配置 */
  const form = reactive({
    state: {
      content: '',
    },
    rule: {
      content: [{ required: true, message: '请输入策略内容' }],
    },
    searchSuccess: false,
    onUserPhoneSearch: () => validate('userPhone'),
  })
  /** 表单hook */
  const { validate, validateInfos, resetFields } = Form.useForm(form.state, form.rule)

  /**
   * 确定
   */
  const onOk = () => {
    validate()
      .then(async () => {
        console.log(JSON.parse(form.state.content))
        const { responseCode } = await requestEditStrategy(JSON.parse(form.state.content))
        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success('编辑成功')
          visible.value = false
          emits('success')
        }
      })
      .catch(() => {})
  }
</script>

<style lang="less" scoped>
  .logo {
    position: absolute;
    top: 0;
    width: 100px;
    height: 100px;
    opacity: 0;
    cursor: pointer;
  }
</style>
